//
//  HXDRetweetedPictureView.swift
//  weibo
//
//  Created by huxuedong on 15/12/11.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit
import SnapKit

private let ID = "cell"
private let column = 3
private let distance: CGFloat = 5
private let imageW: CGFloat = CGFloat(Int(kScreenW - distance * 2 - margin * 2) / column)

class HXDRetweetedPictureView: UICollectionView {
    
    //pictureView大小的约束
    var sizeConstraint: Constraint?
    var pic_urls: [HXDRetweetedPicture]? {
        didSet {
            let size = picViewSize(pic_urls?.count ?? 0)
            self.snp_updateConstraints { (make) -> Void in
                //更新pictureView的大小
                self.sizeConstraint = make.size.equalTo(size).constraint
            }
            reloadData()
        }
    }
    
    private func picViewSize(count: Int) -> CGSize {
        //需要显示的列数
        let column = count == 4 ? 2 : (count >= 3 ? 3 : count)
        //需要显示的行数
        let row = count == 4 ? 2 : ((count - 1) / 3 + 1)
        //图片视图的(pictureView)宽度
        let width  = CGFloat(column) * imageW + CGFloat(column - 1) * distance
        //pictureView的高度
        let height = CGFloat(row) * imageW + CGFloat(row - 1) * distance
        return CGSize(width: width, height: height)
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        backgroundColor = UIColor(white: 0.95, alpha: 1)
        //注册cell
        registerClass(HXDRetweetedPictureViewCell.self, forCellWithReuseIdentifier: ID)
        dataSource = self
        delegate = self
        //设置流水布局
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //每一个条目的大小
        layout.itemSize = CGSize(width: imageW, height: imageW)
        //水平间距
        layout.minimumInteritemSpacing = distance
        //垂直间距
        layout.minimumLineSpacing = distance
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension HXDRetweetedPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    //多少个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }
    
    //每个cell的内容
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ID, forIndexPath: indexPath) as! HXDRetweetedPictureViewCell
        cell.pictureInfo = pic_urls![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //使用第三方显示大图
        let browser = SDPhotoBrowser()
        //原图父控件
        browser.sourceImagesContainerView = self
        //图片张数
        browser.imageCount = pic_urls?.count ?? 0
        //当前图片的索引
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
    }
    
}

//实现框架中必须实现的方法
extension HXDRetweetedPictureView: SDPhotoBrowserDelegate {
    
    //获取图片
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        if let cell = self.cellForItemAtIndexPath(indexPath) as? HXDRetweetedPictureViewCell {
            return cell.imageView.image
        }
        return nil
    }
    
    //获取高清图片的URL
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = pic_urls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail_pic", withString: "bmiddle")
        return NSURL(string: urlString)
    }
    
}

class HXDRetweetedPictureViewCell: UICollectionViewCell {
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        //设置图片填充方式为不拉伸填充
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    private lazy var gifImage: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    var pictureInfo: HXDRetweetedPicture? {
        didSet {
            if let urlString = pictureInfo?.thumbnail_pic {
                //判断图片的URL是否以".git"结尾，如果是则不隐藏
                gifImage.hidden = !urlString.hasSuffix(".gif")
                imageView.sd_setImageWithURL(NSURL(string: urlString), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImage)
        imageView.snp_makeConstraints { (make) -> Void in
            //设置内边距为0
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        gifImage.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.bottom.equalTo(imageView)
        }
    }
    
}
